//
//  KXAddViewController.swift
//  KXBook
//
//  Created by  on 2022/9/9.
//

import UIKit
import CoreLocation
enum KXAddType : Int
{
    case pay = 1
    case In = 2
}

class KXAddViewController: KXViewController {
    @IBOutlet var collectionView: UICollectionView!
    var header:KXHeaderView?
    var typeArray = [KXTypeModel]()
    var model = KXRecord()
    var selectname = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = LS("新增明细")
        self.model.type.isPay = self.model.type.name.count > 0 ? self.model.type.isPay : 1
        self.selectname = self.model.type.name.count > 0 ? self.model.type.name : ""
        self.header = (KXHeaderView.loadFromXIB() as! KXHeaderView)
        self.header!.model = self.model
        weak var weakself = self
        self.header!.bgBtnView.block = { type in
            let typemodel = KXTypeModel()
            typemodel.isPay = type == .pay ? 1 : 0
            weakself?.model.type = typemodel
            weakself?.updateUI()
        }
        self.header!.block = { (type , money, decrip) in
            weakself?.model.money = money
            weakself?.model.descrip = decrip
        }
        self.updateUI()
        self.collectionView.register(KXAddImgCell.nib(), forCellWithReuseIdentifier: KXAddImgCell.ID())
        self.collectionView.register(KXAddTypeCell.nib(), forCellWithReuseIdentifier: KXAddTypeCell.ID())
        self.collectionView.register(KXHeaderView.nib(), forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier:KXHeaderView.ID())
        self.collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier:"header")
        
    }
    func updateUI(){
        let whereStr = String(format:"where %@=%@",bg_sqlKey("isPay"),bg_sqlValue("\(self.model.type.isPay)"))
        KXTypeModel.bg_findAsync(nil, where:whereStr) { array in
            DispatchQueue.main.async {
                self.typeArray = array as? [KXTypeModel] ?? [KXTypeModel]()
                self.collectionView.reloadData()
            }
        }
    }
    @IBAction func actionForBtn(_ sender: UIButton) {
        if self.model.money.count <= 0{
            return Toast.msg(LS("金额不能为空"))
        }else if self.model.descrip.count <= 0{
            return Toast.msg(LS("备注不能为空"))
        }else if self.model.type.name.count <= 0{
            return Toast.msg(LS("类型不能为空"))
        }else if self.model.datas.count <= 0{
            return Toast.msg(LS("至少上传一张图片"))
        }
        let oldstamp = "\(self.model.stamp)"
        let stamp = NSDate.currentTimeStamp("yyyy/MM/dd hh:mm:ss").intValue()
        let date = NSDate.dateOfStamp(stamp)
        self.model.stamp = Int32(stamp)
        self.model.year = "\(date.year!)"
        self.model.month = "\(date.month!)"
        self.model.day = "\(date.day!)"
        self.model.week = "\(date.weekday!)"
        self.model.userID = APP.user.id
        Toast.startHud(LS("保存中..."))
        if oldstamp.intValue() > 0 {
            let whereStr = String(format:"where %@=%@",bg_sqlKey("stamp"),bg_sqlValue(oldstamp))
            KXRecord.bg_deleteAsync(nil, where:whereStr) { success in
            }
        }
        self.model.bg_saveOrUpdateAsync({ success in
            DispatchQueue.main.async {
                Toast.stopHud()
                NotifyTool.post(NotifyName.updateRecord)
                self.navigationController?.popToRootViewController(animated: true)
            }
        })
    }
    
    func addPicture()
    {
        weak var weakself = self
        weakself?.sheet(nil, nil, ["相机","相簿"], { index, sheetTitle in
            DispatchQueue.main.async {
                Toast.startHud()
            }
            let  vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = true
            vc.sourceType = index == 0 ? .camera : .photoLibrary
            vc.modalPresentationStyle = .overFullScreen
            weakself?.present(vc, animated: true, completion: {
                Toast.stopHud()
            })
        })
    }
    
}

//MARK: - UIImagePickerControllerDelegate / UINavigationControllerDelegate
extension KXAddViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated:true, completion:nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let img : UIImage = info[.editedImage] as! UIImage
        let data = img.jpegData(compressionQuality: 0.5)
        self.model.datas.add(data as! NSData)
        self.collectionView.reloadData()
        picker.dismiss(animated:false, completion: nil)
    }
}


//MARK: - UICollectionViewDataSource
extension KXAddViewController : UICollectionViewDataSource
{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return section == 0 ? self.typeArray.count : self.model.datas.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier:KXAddTypeCell.ID(), for: indexPath) as! KXAddTypeCell
            let model = self.typeArray[indexPath.row]
            cell.img.image = UIImage(named:model.icon)
            cell.type.text = LS(model.name)
            cell.bgImg.bgHexColor = self.selectname == model.name ? "#E27BC1" : "#969696"
            return cell
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier:KXAddImgCell.ID(), for: indexPath) as!  KXAddImgCell
            cell.deleteBtn.isHidden = indexPath.row == self.model.datas.count
            cell.plus.isHidden = indexPath.row != self.model.datas.count
            cell.img.image = nil
            if indexPath.row < self.model.datas.count{
                cell.img.image = UIImage(data: self.model.datas[indexPath.row] as! Data)!
            }
            cell.deleteBlock = {
                self.model.datas.removeObject(at: indexPath.row)
                collectionView.reloadData()
            }
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if indexPath.section == 0{
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier:"header", for: indexPath)
            self.header?.frame = CGRect(x: 0, y: 0, width: kUIScreenWidth, height:220)
            view.addSubview(self.header!)
            return view
        }else{
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier:"header", for: indexPath)
            let lbl = UILabel()
            lbl.frame = CGRect(x:20, y: 18, width: 100, height: 20)
            lbl.text = LS("上传图片")
            lbl.font = font(14)
            lbl.textHexColor = "#3D3D3D"
            view.addSubview(lbl)
            return view
        }
        
    }
    
}
//MARK: - UICollectionViewDelegate
extension KXAddViewController : UICollectionViewDelegate
{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 0{
            let ispay = self.model.type.isPay
            self.model.type = self.typeArray[indexPath.row]
            self.model.type.isPay = ispay
            self.selectname = self.model.type.name
            collectionView.reloadData()
        }else if indexPath.section == 1 && indexPath.row == self.model.datas.count{
            self.addPicture()
        }
    }
}

//MARK: - UICollectionViewDelegateFlowLayout
extension KXAddViewController : UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        if indexPath.section == 0{
            return CGSize(width: 60, height: 80)
        }else{
            return CGSize(width:80, height:80)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
    {
        return section == 0 ? 40 : 30
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {
        return 20
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top:20, left: 30, bottom: 0, right: 30)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let h = section == 0 ? 220 : 38
        return CGSize(width:kUIScreenWidth, height: CGFloat(h))
    }
    
    
}
